<?php

namespace App\Http\Middleware;

use App\Util\Tool;
use Closure;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;

class ApiAuth
{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $tokenString = (string)$request->header("access-token");

        $app_key = env('ACCESS_TOKEN');
        if (empty($tokenString)) {
            return response()->json(['code' => 0, 'msg' => '请申请access-token秘钥', 'data' => null]);
        }

        if ($app_key != $tokenString) {
            return response()->json(['code' => 0, 'msg' => '请申请access-token秘钥', 'data' => null]);
        }
        $api_token = $request->api_token ?? '';
        if ($api_token == "") {
            return response()->json(['code' => 0, 'msg' => 'api_token不能为空', 'data' => null]);
        }
        //检查api_token是否正确
        if (!Tool::GetLoginToken($api_token)) {
            return response()->json(['code' => 3, 'msg' => 'api_token过期', 'data' => null]);
        }
        //更新token
        Tool::SetAndUpToken($api_token, null);
        return $next($request);

    }
}
